package com.xxx.reggie.service.impl;

import com.xxx.reggie.entity.User;
import com.xxx.reggie.exception.BusinessException;
import com.xxx.reggie.mapper.UserMapper;
import com.xxx.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;
    /**
     * 登入校验的方法
     *
     * @param phone       用户号码
     * @param code        用户输入的验证码
     * @param sessionCode session的验证码
     * @return User 登入的用户
     */
    @Override
    public User UserByPhone(String phone, String code, String sessionCode) {
        //1.传递过来手机号,用户输入验证码与session的验证码
        //2.校验验证码是否正确,如果不正确返回"验证码错误"
        if (!code.equalsIgnoreCase(sessionCode)){
            throw  new BusinessException("验证码错误");
        }
        //3.根据手机号查找用户对象,如果找到直接返回
        User userByPhone = userMapper.UserByPhone(phone);
        //4.如果没找到,
        if (userByPhone==null){
        //5.就完善用户信息(设置状态为1正常),并添加用户到数据库
            userByPhone = new User();
            userByPhone.setPhone(phone); //添加用户号码
            userByPhone.setStatus(1); //添加默认状态为1
            userMapper.save(userByPhone);
        }

        //5.返回登入用户对象
        return userByPhone;
    }
}
